<template>
  <div class="tags-container">
    <!-- 标签操作区 -->
    <el-card class="operation-card">
      <template #header>
        <div class="card-header">
          <span>标签管理</span>
          <div class="header-operations">
            <el-button type="primary" @click="showCreateDialog = true">
              创建标签
            </el-button>
            <el-button @click="handleBatchImport">批量导入</el-button>
            <el-button @click="handleExport">导出标签</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索标签"
          style="width: 200px"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-select v-model="tagType" placeholder="标签类型" clearable @change="handleSearch">
          <el-option label="系统标签" :value="0" />
          <el-option label="用户标签" :value="1" />
        </el-select>
      </div>

      <!-- 标签列表 -->
      <el-table
        :data="tagList"
        style="width: 100%"
        v-loading="tableLoading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="tagName" label="标签名称" />
        <el-table-column prop="tagColor" label="标签颜色" width="100">
          <template #default="{ row }">
            <el-tag :color="row.tagColor">{{ row.tagName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="tagType" label="标签类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.tagType === 0 ? 'info' : ''">
              {{ row.tagType === 0 ? '系统标签' : '用户标签' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDelete(row)"
                :disabled="row.tagType === 0"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑标签对话框 -->
    <el-dialog
      :title="editingTag.id ? '编辑标签' : '创建标签'"
      v-model="showCreateDialog"
      width="500px"
    >
      <el-form :model="editingTag" :rules="rules" ref="tagFormRef" label-width="80px">
        <el-form-item label="标签名称" prop="tagName">
          <el-input v-model="editingTag.tagName" />
        </el-form-item>
        <el-form-item label="标签颜色" prop="tagColor">
          <el-color-picker v-model="editingTag.tagColor" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSaveTag" :loading="saving">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      title="批量导入标签"
      v-model="showImportDialog"
      width="500px"
    >
      <el-form :model="importForm" :rules="importRules" ref="importFormRef" label-width="100px">
        <el-form-item label="标签名称" prop="tagNames">
          <el-input
            v-model="importForm.tagNames"
            type="textarea"
            rows="4"
            placeholder="请输入标签名称，多个标签用逗号分隔"
          />
        </el-form-item>
        <el-form-item label="标签颜色" prop="tagColor">
          <el-color-picker v-model="importForm.tagColor" />
        </el-form-item>
        <el-form-item label="导入选项">
          <el-checkbox v-model="importForm.skipDuplicate">跳过重复标签</el-checkbox>
          <el-checkbox v-model="importForm.batchCommit">批量提交</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showImportDialog = false">取消</el-button>
          <el-button type="primary" @click="handleImportSubmit" :loading="importing">
            导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { tagApi } from '../../api/tag'
import { getUserId } from '../../utils/user'

// 列表相关
const tableLoading = ref(false)
const tagList = ref([])
const searchKeyword = ref('')
const tagType = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedTags = ref([])

// 创建/编辑相关
const showCreateDialog = ref(false)
const tagFormRef = ref(null)
const saving = ref(false)
const editingTag = reactive({
  id: '',
  tagName: '',
  tagColor: '#409EFF',
  tagType: 1
})

const rules = {
  tagName: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  tagColor: [
    { required: true, message: '请选择标签颜色', trigger: 'change' }
  ]
}

// 批量导入相关
const showImportDialog = ref(false)
const importFormRef = ref(null)
const importing = ref(false)
const importForm = reactive({
  tagNames: '',
  tagColor: '#409EFF',
  skipDuplicate: true,
  batchCommit: true
})

const importRules = {
  tagNames: [
    { required: true, message: '请输入标签名称', trigger: 'blur' }
  ],
  tagColor: [
    { required: true, message: '请选择标签颜色', trigger: 'change' }
  ]
}

// 加载标签列表
const loadTagList = async () => {
  try {
    tableLoading.value = true
    const res = await tagApi.page({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value,
      tagType: tagType.value,
      // userId 会在 API 层自动添加
    })
    
    if (res.data) {
      tagList.value = res.data.records || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('Load tags error:', error)
    ElMessage.error('获取标签列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadTagList()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  loadTagList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadTagList()
}

// 选择
const handleSelectionChange = (selection) => {
  selectedTags.value = selection
}

// 创建/编辑标签
const handleEdit = (row) => {
  Object.assign(editingTag, row)
  showCreateDialog.value = true
}

const handleSaveTag = async () => {
  if (!tagFormRef.value) return
  
  try {
    await tagFormRef.value.validate()
    saving.value = true
    
    if (editingTag.id) {
      await tagApi.update(editingTag)
      ElMessage.success('更新成功')
    } else {
      await tagApi.create(editingTag)
      ElMessage.success('创建成功')
    }
    
    showCreateDialog.value = false
    loadTagList()
  } catch (error) {
    ElMessage.error(error.message || '操作失败')
  } finally {
    saving.value = false
  }
}

// 删除标签
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该标签吗？', '提示', {
      type: 'warning'
    })
    await tagApi.delete({
      tagId: row.id,
      userId: getUserId()
    })
    ElMessage.success('删除成功')
    loadTagList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量导入
const handleBatchImport = () => {
  showImportDialog.value = true
}

const handleImportSubmit = async () => {
  if (!importFormRef.value) return
  
  try {
    await importFormRef.value.validate()
    importing.value = true
    
    const tagNames = importForm.tagNames.split(',').map(name => name.trim())
    await tagApi.import({
      ...importForm,
      tagNames,
      userId: localStorage.getItem('userId')
    })
    
    ElMessage.success('导入成功')
    showImportDialog.value = false
    loadTagList()
  } catch (error) {
    ElMessage.error(error.message || '导入失败')
  } finally {
    importing.value = false
  }
}

// 导出标签
const handleExport = async () => {
  try {
    await tagApi.export({
      userId: localStorage.getItem('userId')
    })
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

onMounted(() => {
  loadTagList()
})
</script>

<style scoped>
.tags-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.search-area {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card__header) {
  padding: 15px 20px;
}
</style> 